package com.usian.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.usian.feign.UserFeign;
import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Value("${config.info}")
    private String config;
    @RequestMapping("findById/{id}")
    public User findById(@PathVariable Integer id){
        ServiceInstance instance = loadBalancerClient.choose("provider");
        String url= "http://"+instance.getHost()+":"+instance.getPort()+"/findById/"+id;
        User user = restTemplate.getForObject(url, User.class);
        System.out.println("======"+config);
        return user;

    }
    @Autowired
    private UserFeign userFeign;

    @RequestMapping("findByIds/{id}")
    @SentinelResource(value = "findByIds/{id}",blockHandler = "blockTest",fallback = "fallTest")
    public User findByIds(@PathVariable Integer id){
//        int i=1/0;
        User user = userFeign.findById(id);
        return user;
    }
    public User blockTest(@PathVariable Integer id, BlockException e){
        return new User(1,"block",2);
    }
    public User fallTest(@PathVariable Integer id, Throwable e){
        return new User(0,"fall",2);
    }
    @GetMapping("findByName")
    public User findByName(Integer id){
        return userFeign.findById(id);
    }

    @PostMapping("findByUser")
    public User findByUser(@RequestBody User user){
        return userFeign.findById(user.getId());
    }
}
